/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package parser.nodes;

import codegen.CodeGen;
import java.util.ArrayList;
import java.util.List;
import parser.Pair;
import scanner.Token;

// SimpleExpression = ['-'] Term {('+' | '-') Term}
public class SimpleExpressionNode extends Node {
    private Token minus;
    private TermNode term;
    private List<Pair<Token,TermNode>> terms = new ArrayList<>();
    
    public SimpleExpressionNode(Token minus, TermNode term) {
        this.minus = minus;
        this.term = term;
    }
    
    public SimpleExpressionNode(TermNode term) {
        this(null, term);
    }
    
    public void addTerm(Token operator, TermNode term) {
        terms.add(new Pair<>(operator, term));
    }
    
	public void removeCont() {
		if (terms.isEmpty() && minus == null)
			term.removeCont();
	}
	
    @Override
    public void print() { 
        p("SimpleExpression:");
        indent();
        if (minus != null) 
            p(minus);
        term.print();
        for(Pair<Token,TermNode> pair : terms) {
            p(pair.getFirst());
            pair.getSecond().print();
        }
        unindent();
    }

    @Override
    public void abstractPrint() {
        if (minus != null)
            p(minus);
        term.abstractPrint();
        for(Pair<Token,TermNode> summand : terms) {
            p(summand.getFirst());
            indent();
            summand.getSecond().abstractPrint();
            unindent();
        }
    }

    @Override
    public void compile(CodeGen c) throws CompileError {
        if (minus != null)
            c.outstr("PUSHI, 0");
        
        term.compile(c);
        
        for(Pair<Token,TermNode> summand : terms) {
            summand.getSecond().compile(c);
            if (summand.getFirst().is("-"))
                c.outstr("SUB");
            else 
                c.outstr("ADD");
        }
        
        if (minus != null)
            c.outstr("SUB");
    }
    
    
}
